package com.matrix.im.netty;

import com.matrix.im.netty.handler.AuthHandler;
import com.matrix.im.netty.handler.HeartbeatHandler;
import com.matrix.im.netty.handler.MessageHandler;
import com.matrix.im.protocol.MessageProto;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 有点甜
 * @since 2025/8/6
 */
@Component
@RequiredArgsConstructor
public class IMChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final HeartbeatHandler heartbeatHandler;
    private final AuthHandler authHandler;
    private final MessageHandler messageHandler;

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("idleStateHandler", new IdleStateHandler(45, 0, 0, TimeUnit.SECONDS));
        pipeline.addLast("heartbeatHandler", heartbeatHandler);
        pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
        pipeline.addLast("protobufDecoder", new ProtobufDecoder(MessageProto.MessagePackage.getDefaultInstance()));
        pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast("protobufEncoder", new ProtobufEncoder());
        pipeline.addLast("authHandler", authHandler);
        pipeline.addLast("messageHandler", messageHandler);
    }
}
